package com.wei.controller.front;

import cn.hutool.core.util.StrUtil;
import com.wei.client.OrderClientFeign;
import com.wei.entity.vo.BaseCourseVo;
import com.wei.entity.vo.ChapterVo;
import com.wei.entity.vo.CourseQueryVo;
import com.wei.service.ChapterService;
import com.wei.service.CourseService;
import com.wei.service_base.vo.CourseOrderVo;
import com.wei.utils.JwtUtils;
import com.wei.utils.R;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * @author wjx
 * @ClassName CourseFrontController
 * @description: TODO
 * @date 2022-12-02 13:11
 * @version: 1.0
 */
@RestController
@RequestMapping("/eduservice/frontCourse")

public class CourseFrontController {

    @Autowired
    private CourseService courseService;

    @Autowired
    private ChapterService chapterService;

    @Autowired
    private OrderClientFeign orderClientFeign;

    @PostMapping("/getCoursePage/{current}/{limit}")
    public R getCoursePage(@PathVariable Long current,
                           @PathVariable Long limit,
                           @RequestBody(required = false) CourseQueryVo courseQueryVo) {

        Map<String, Object> map = courseService.queryCoursePage(current, limit, courseQueryVo);

        return R.ok().data("map", map);
    }

    @GetMapping("/getBaseCourseInfo/{courseId}")
    public R getBaseCourseInfo(@PathVariable("courseId") String courseId, HttpServletRequest request) {

        //根据课程id获取课程相关信息
        BaseCourseVo baseCourseVo = courseService.getCourseInfoById(courseId);

        Integer buyCount = orderClientFeign.buyCount(courseId);
        baseCourseVo.setBuyCount(buyCount.longValue());

        //根据课程id获取章节和小节信息
        List<ChapterVo> chapterVideoList = chapterService.getChapterVideoByCid(courseId);

        //根据课程id和用户id查询课程是否已经完成购买
        String memberId = JwtUtils.getMemberIdByJwtToken(request);

        boolean isBuy = false;
        if (StrUtil.isNotEmpty(memberId)) {
            isBuy = orderClientFeign.queryPayStatus(courseId, memberId);
        }

        return R.ok().data("baseCourseVo", baseCourseVo)
                .data("chapterVideoList", chapterVideoList)
                .data("isBuy", isBuy);
    }

    /**
     * 用于生成订单
     *
     * @param courseId
     * @return
     */
    @GetMapping("/getCourseOrderInfo/{courseId}")
    public CourseOrderVo getCourseOrderInfo(@PathVariable String courseId) {

        BaseCourseVo baseCourseVo = courseService.getCourseInfoById(courseId);

        CourseOrderVo courseOrderVo = new CourseOrderVo();
        BeanUtils.copyProperties(baseCourseVo, courseOrderVo);

        return courseOrderVo;
    }


}
